<template>
  <view class="branch-invest-container">
    <div class="loading-container" v-show="loading">
      <u-loading mode="circle" show />
    </div>
    <view v-if="canEdit" class="container-header">
      <view class="opreater" @click="handleEdit">
        <image width="34rpx" height="34rpx" src="../../static/edit-icon.png"></image>
        <view style="margin-left: 12rpx;">编辑</view>
      </view>
    </view>
    <view class="container-body">
      <view class="order-item" v-for="col in cols" :key="col.value">
        <view class="order-item-label">
          <view v-for="l in col.label" :key="l">{{ l }}</view>
        </view>
        <view class="order-item-value">{{ orderDetail[col.value] }}</view>
      </view>
      <view class="order-item">
        <view class="order-item-label">
          <view v-for="l in '创建时间'" :key="l">{{ l }}</view>
        </view>
        <view class="order-item-value">
          <view>{{ orderDetail.createTime }}</view>
        </view>
      </view>
      <view class="order-item">
        <view class="order-item-label">
          <view v-for="l in '创建人'" :key="l">{{ l }}</view>
        </view>
        <view class="order-item-value">
          <view>{{ orderDetail.custName }}</view>
        </view>
      </view>
      <view class="order-item">
        <view class="order-item-label">
          <view v-for="l in '状态'" :key="l">{{ l }}</view>
        </view>
        <view class="order-item-value" >
          <view>{{ orderDetail.status | statusFilter }}</view>
        </view>
      </view>
      <!-- 启动状态 -->
      <view class="order-item" v-if="orderDetail.investmentManagerName">
        <view class="order-item-label">
          <view v-for="l in '招商负责人'" :key="l">{{ l }}</view>
        </view>
        <view class="order-item-value">
          <view>{{ orderDetail.investmentManagerName }}</view>
        </view>
      </view>
      <view class="order-item" v-if="['1', '4'].includes(orderDetail.status)">
        <view class="order-item-label">
          <view v-for="l in '启动时间'" :key="l">{{ l }}</view>
        </view>
        <view class="order-item-value">
          <view>{{ orderDetail.startTime }}</view>
        </view>
      </view>
      <view class="order-item" v-if="orderDetail.status === '1' && orderDetail.planCompleteTimeList && orderDetail.planCompleteTimeList.length > 0">
        <view class="order-item-label">
          <view v-for="l in '预计完成时间'" :key="l">{{ l }}</view>
        </view>
        <view class="order-item-value" style="display: flex;align-items: flex-end;">
          <view >
            <view v-for="time in orderDetail.planCompleteTimeList" :key="time">{{ time }}</view>
          </view>
          <!-- 需要逾期才可以更改 orderDetail.overdue -->
          <image v-if="canSuccess && orderDetail.overdue" style="margin-bottom: 10rpx;" @click="handleEditCompleteTime" class="edit-icon" src="../../static/toStore/timeEdit-icon.png"></image>
        </view>
      </view>
      <view class="order-item" v-if="orderDetail.status === '1'">
        <view class="order-item-label">
          <view v-for="l in '是否超期'" :key="l">{{ l }}</view>
        </view>
        <view class="order-item-value">
          <view>{{ orderDetail.overdue ? '是' : '否' }}</view>
        </view>
      </view>
      <!-- 关闭状态 -->
      <view class="order-item" v-if="orderDetail.status === '3'">
        <view class="order-item-label">
          <view v-for="l in '关闭时间'" :key="l">{{ l }}</view>
        </view>
        <view class="order-item-value">
          <view>{{ orderDetail.closingTime }}</view>
        </view>
      </view>
      <view class="order-item" v-if="orderDetail.status === '3'">
        <view class="order-item-label">
          <view v-for="l in '关闭人'" :key="l">{{ l }}</view>
        </view>
        <view class="order-item-value">
          <view>{{ orderDetail.closingUserName }}</view>
        </view>
      </view>
      <view class="order-item" v-if="orderDetail.status === '3'">
        <view class="order-item-label">
          <view v-for="l in '关闭原因'" :key="l">{{ l }}</view>
        </view>
        <view class="order-item-value">
          <view>{{ orderDetail.shutdownReason  }}{{ orderDetail.otherShutdownReason ? `(${orderDetail.otherShutdownReason})` : '' }}</view>
        </view>
      </view>
      <!-- 完成状态 -->
      <view class="order-item" v-if="orderDetail.status === '4'">
        <view class="order-item-label">
          <view v-for="l in '店面名称'" :key="l">{{ l }}</view>
        </view>
        <view class="order-item-value">
          <view>{{ orderDetail.storeName }}</view>
        </view>
      </view>
      <view class="order-item" v-if="orderDetail.status === '4'">
        <view class="order-item-label">
          <view v-for="l in '店面代码'" :key="l">{{ l }}</view>
        </view>
        <view class="order-item-value">
          <view>{{ orderDetail.storeA8  || '<空>' }}</view>
        </view>
      </view>
      <view class="order-item" v-if="orderDetail.status === '4'">
        <view class="order-item-label">
          <view v-for="l in '完成时间'" :key="l">{{ l }}</view>
        </view>
        <view class="order-item-value">
          <view>{{ orderDetail.completionTime }}</view>
        </view>
      </view>
      <view class="order-item" v-if="orderDetail.status === '4'">
        <view class="order-item-label">
          <view v-for="l in '完成人'" :key="l">{{ l }}</view>
        </view>
        <view class="order-item-value">
          <view>{{ orderDetail.updateByName }}</view>
        </view>
      </view>
    </view>
    <view class="container-footer" v-if="canClose || canStart || canSuccess">
      <u-button v-if="canClose" shape="circle" @click="handleClose">关闭</u-button>
      <u-button v-if="canStart" shape="circle" type="warning" @click="handleStart">启动</u-button>
      <u-button v-if="canSuccess" shape="circle" type="success" @click="handleDone">完成</u-button>
    </view>
    <!-- 模态视图 -->
     <!-- 关闭原因 -->
    <u-modal
      ref="closeModal"
      v-model="isCloseVisible"
      title="关闭原因"
      :width="`${screenWidth}px`"
      show-cancel-button
      z-index="998"
      async-close
			:title-style="{
				borderBottom: 'solid #F5F6F8 2rpx',
				fontSize: '32rpx',
				paddingTop: '28rpx',
				paddingBottom: '28rpx'
			}"
			:confirm-style="{
				borderLeft: 'solid #F5F6F8 2rpx',
			}"
      @confirm="handleCloseConfirm"
    >
      <view class="edit-form">
        <uni-data-select
          v-model="closeReason"
          :localdata="closeReasonOpts"
          @change="actionSheetCallback"
          class="custom-uni-field"
        >
      </uni-data-select>
      <view v-if="closeReason === '其他'" style="margin-top: 120rpx">
        <u-input
          v-model="otherCloseReason"
          type="textarea"
          placeholder="请输入关闭原因"
          :height="350"
          class="custom-field"
        />
        </view>
      </view>
    </u-modal>
    <!-- 启动--选择预计完成日期 -->
    <u-calendar
      v-model="isStartVisible"
      toolTip="预计完成时间"
      mode="date"
      @change="handleStartConfirm"
      :min-date="todayString"
			max-date="2050-12-31"
    ></u-calendar>
    <!-- 修改预计完成时间 -->
    <u-modal
      ref="editCompleteTimeModal"
      v-model="isEditTimeVisible"
      title="修改完成时间"
      :width="`${screenWidth}px`"
      show-cancel-button
      z-index="998"
      async-close
			:title-style="{
				borderBottom: 'solid #F5F6F8 2rpx',
				fontSize: '32rpx',
				paddingTop: '28rpx',
				paddingBottom: '28rpx'
			}"
			:confirm-style="{
				borderLeft: 'solid #F5F6F8 2rpx',
			}"
      @confirm="handleEditCompleteTimeConfirm"
    >
      <u-form :model="editTimeFormData" class="editTime-form" ref="editForm">
        <u-form-item label-width="0rpx" :border-bottom="false" prop="date">
          <u-input
            v-model="editTimeFormData.date"
            class="custom-field input"
            placeholder="请选择时间"
            type="select"
            @click="isSelectNewTime = true"
          />
        </u-form-item>
        <u-form-item label-width="0rpx" :border-bottom="false" prop="reason">
          <u-input
            v-model="editTimeFormData.reason"
            type="textarea"
            placeholder="请输入修改原因"
            :height="350"
            class="custom-field"
          />
        </u-form-item>
      </u-form>
    </u-modal>
      <!-- 逾期--选择预计完成日期 -->
    <u-calendar
      v-model="isSelectNewTime"
      toolTip="预计完成时间"
      mode="date"
      @change="handleOverTimeChange"
      :min-date="todayString"
      max-date="2050-12-31"
    ></u-calendar>
    <!-- 助店打卡选择助店的店面 -->
		<view class="store-select-shdow" v-if="isSelectStoreVisible"></view>
		<view class="store-select-toast" v-if="isSelectStoreVisible">
			<view class="toast-clone" @click="isSelectStoreVisible = false"></view>
			<view class="store-search">
				<input v-model="storeSearchValue" focus type="text" :border="false" @input="storeListSearch" placeholder="请输入门店名称搜索" />
			</view>
			<view class="store-list">
				<scroll-view class="scroll-Y" :scroll-top="0" scroll-y="true">
					<view class="store-list-item" v-for="item in allStoreList" :key="item.storeName" @click="handleDoneConfirm(item)">{{item.storeName}}</view>
				</scroll-view>
			</view>
		</view>
    <!-- toast -->
    <u-toast ref="uToast" z-index="99999999" />
  </view>
</template>

<script>
import {
  getBranchInvestOrderDetail,
  getSystemDictData,
  startBranchInvestOrder,
  changeBranchInvestOrderOvertime,
  closeBranchInvestOrder,
  completeBranchInvestOrder,
  getStoreList,
} from "../../common/service.js";
import uFormItem from '../../uview-ui/components/u-form-item/u-form-item.vue';
const cols = [
  { label: '省份', value: 'province' },
  { label: '城市', value: 'city' },
  { label: '区县', value: 'area' },
  { label: '街道', value: 'street' },
  { label: '品牌', value: 'brand' },
  { label: '市场类型', value: 'marketType' },
  { label: '市场名称', value: 'marketName' },
  { label: '详细地址', value: 'marketAddress' },
]
export default {
  components: { uFormItem },
  data() {
    const { screenWidth } = uni.getWindowInfo();
    return {
      screenWidth: screenWidth - 36,
      orderId: null,
      orderDetail: {},
      cols,
      closeReasonOpts: [],
      loading: false,
      isCloseVisible: false,
      closeReason: '',
      otherCloseReason: '',
      isStartVisible: false,
      todayString: this.$u.timeFormat(new Date(), 'yyyy-mm-dd'),
      isSelectNewTime: false,
      isEditTimeVisible: false,
      editTimeFormData: {
        date: '',
        reason: ''
      },
      isSelectStoreVisible: false,
      allStoreList: [],
      storeSearchValue: '',
    }
  },
  onLoad(option) {
    const { id } = option;
    this.orderId = id;
    this.move();
  },
  onShow() {
    if (this.orderId) {
      this.fetchDetail(this.orderId);
    }
  },
  filters: {
    statusFilter(v) {
      return {
        0: '新建',
        1: '已启动',
        2: '已超期',
        3: '已关闭',
        4: '已完成',
      }[v] || '未知'
    }
  },
  computed: {
    uid() {
      return this.CONFIG.user.id.toLowerCase();
    },
    // 新建状态 创建人可编辑
    canEdit() {
      const { createBy, status } = this.orderDetail
      return status === '0'
    },
    isCreatorOrManager() {
      const { createBy, status, investmentManager } = this.orderDetail;
      return createBy === this.uid || investmentManager === this.uid;
    },
    // 启动状态才允许变更，创建人和招商负责人
    canSuccess() {
      const { status } = this.orderDetail
      return status === '1'
    },
    // 新建和启动状态可以关闭，创建人和招商负责人操作
    canClose() {
      const { status } = this.orderDetail;
      return ['0', '1'].includes(status)
    },
    canStart() {
      const { status } = this.orderDetail
      return status === '0'
    }
  },
  created() {
    this.fetchCloseReasonOpts();
  },
  methods: {
    // 允许页面滚动
    move() {
      var box = function (e) {
        passive: false
      };
      document.body.style.overflow = ''; // 出现滚动条
      document.removeEventListener("touchmove", box, false);
    },
    fetchDetail(id) {
      if (!id) return;
      this.loading = true;
      getBranchInvestOrderDetail(id, (result) => {
        this.loading = false;
        if (!result || result.statusCode !== 200) {
          return;
        }
        const { data: rs } = result;
        if (rs.code === 200) {
          this.orderDetail = rs.data;
        } else {
          this.$refs.uToast.show({
            title: `获取详情失败：${rs.msg}`,
            type: "error", // primary / success / error / warning / info
            duration: 2000,
          });
        }
      }, () => {
        this.loading = false;
      })
    },
    // 店铺选择输入查询/模糊查询
    storeListSearch(e){
      this.storeSearchValue = e.detail.value;
      // 请求查询接口
      this.debounceSeachStoreList();
    },
    debounceSeachStoreList() {
      this.$u.debounce(this.queryStoreList, 500)
    },
    // 模糊查询门店接口
     queryStoreList(){
      const that = this
      if (!this.storeSearchValue) {
        this.allStoreList = [];
        return;
      }
      const params = {
        code: this.CONFIG.user.id,
        storeName: this.storeSearchValue || ''
      }
      getStoreList(params, function(resuser) {
        if (resuser && resuser.statusCode == 200) {
          const res = resuser.data;
          that.allStoreList = res.data
          if (!res.data || res.data.length === 0) {
            that.$refs.uToast.show({
            title: '未搜索到门店',
            type: "warning", // primary / success / error / warning / info
            duration: 2000,
          });
          }
        }
      }, function(e) {
      });
    },
			
    handleClose() {
      this.isCloseVisible = true;
      this.closeReason = '';
      this.otherCloseReason = '';
    },
    // 点击actionSheet回调
    actionSheetCallback(index) {
      this.closeReason = this.closeReasonOpts[index].text;
    },
    handleCloseConfirm() {
      if (!this.closeReason) {
        this.$refs.uToast.show({
          title: "请选择关闭原因",
          type: "error",
          duration: 2000,
        });
        this.$refs.closeModal.clearLoading();
        return Promise.reject("请选择关闭原因");
      }
      if (this.closeReason === '其他' && !this.otherCloseReason) {
        this.$refs.uToast.show({
          title: "请输入其他关闭原因",
          type: "error",
          duration: 2000,
        });
        this.$refs.closeModal.clearLoading();
        return Promise.reject("请输入其他关闭原因");
      }
      closeBranchInvestOrder({
        id: this.orderId,
        shutdownReason: this.closeReason,
        otherShutdownReason: this.otherCloseReason
      }, (res) => {
        this.$refs.closeModal.clearLoading();
        const { statusCode, data = {} } = res;
        if (statusCode === 200 && data.code === 200) {
          this.isCloseVisible = false;
          this.$refs.uToast.show({
            title: '关闭成功，正在跳转',
            type: "success", // primary / success / error / warning / info
            duration: 1000,
            callback: () => {
              this.gotoList();
            }
          });
        } else {
          this.$refs.uToast.show({
            title: `关闭失败：${data.msg}`,
            type: "error", // primary / success / error / warning / info
            duration: 2000,
          });
        }
      }, () => {
        this.$refs.closeModal.clearLoading();
      })
    },
    handleDone() {
      this.storeSearchValue = '';
      this.allStoreList = [];
      this.isSelectStoreVisible = true;
    },
    handleDoneConfirm(store) {
      this.loading = true;
      completeBranchInvestOrder({
        id: this.orderId,
        storeName: store.storeName,
        storeA8: store.storeA8,
      }, (result) => {
        this.loading = false;
        if (!result || result.statusCode !== 200) {
          return;
        }
        const { data: rs } = result;
        if (rs.code === 200) {
          this.$refs.uToast.show({
            title: "已完成，正在跳转",
            type: "success",
            duration: 1000,
            callback: () => {
              this.gotoList();
            }
          });
          this.isSelectStoreVisible = false;
        } else {
          this.$refs.uToast.show({
            title: `完成失败：${rs.msg}`,
            type: "error",
            duration: 2000,
          });
        }
      }, () => {
        this.loading = false;
      })
    },
    handleStartConfirm(e) {
      this.loading = true;
      startBranchInvestOrder({ id: this.orderId, strInvestPlanCompletionTime: e.result  }, (result) => {
        this.loading = false;
        if (!result || result.statusCode !== 200) {
          return;
        }
        const { data: rs } = result;
        if (rs.code === 200) {
          this.$refs.uToast.show({
            title: "启动成功，正在跳转",
            type: "success",
            duration: 1000,
            callback: () => {
              this.gotoList();
            }
          });
        } else {
          this.$refs.uToast.show({
            title: `启动失败：${rs.msg}`,
            type: "error",
            duration: 2000,
          });
        }
      }, () => {
        this.loading = false;
      })
    },
    handleOverTimeChange(e) {
      this.editTimeFormData.date = e.result;
    },
    handleEditCompleteTime() {
      this.isEditTimeVisible = true;
      this.editTimeFormData = { date: '', reason: '' }
      setTimeout(() => {
        this.$refs.editForm.setRules({
          date: [{ required: true, message: "请选择日期" }],
          reason: [{ required: true, message: "请填写修改原因" }],
        })
      }, 100);
    },
    handleEditCompleteTimeConfirm() {
      this.$refs.editForm.validate((valid) => {
        if (!valid) {
          this.$refs.editCompleteTimeModal.clearLoading();
          return
        };
        changeBranchInvestOrderOvertime({
          id: this.orderId,
          overdueReason: this.editTimeFormData.reason,
          strInvestPlanCompletionTime: this.editTimeFormData.date
        }, (res) => {
          this.$refs.editCompleteTimeModal.clearLoading();
          const { statusCode, data = {} } = res;
          if (statusCode === 200 && data.code === 200) {
            this.isEditTimeVisible = false;
            this.$refs.uToast.show({
              title: '修改成功，正在跳转',
              type: "success", // primary / success / error / warning / info
              duration: 1000,
              callback: () => {
                this.gotoList();
              }
            });
          } else {
            this.$refs.uToast.show({
              title: `修改失败：${data.msg}`,
              type: "error", // primary / success / error / warning / info
              duration: 2000,
            });
          }
        }, () => {
          this.$refs.editCompleteTimeModal.clearLoading();
        })
      });
    },
    handleStart() {
      this.isStartVisible = true;
    },
    handleEdit() {
      uni.navigateTo({
        url: './create?id=' + this.orderId
      });
    },
    gotoList() {
      uni.navigateTo({
        url: './list'
      });
    },
    fetchCloseReasonOpts() {
      getSystemDictData("BRANCH_CLOSE_REASON", (result) => {
        if (result && result.statusCode == 200) {
            const { data: rs } = result;
            if (rs.code == 200) {
              this.closeReasonOpts = (rs.data || []).map((item) => ({
                text: item.dictLabel,
                value: item.dictLabel,
              }));
            } else {
              this.$refs.uToast.show({
                title: rs.msg || "获取关闭原因失败",
                type: "error",
                duration: 2000,
              });
            }
          }
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.branch-invest-container {
  padding-top: 20rpx;
  background: #F3F5F7;
  // height: 100vh;
}
.container-header {
  display: flex;
  justify-content: flex-end;
  padding: 14rpx 30rpx 24rpx 30rpx;
  color: #007AFF;
}
.opreater {
  display: flex;
  align-items: center;
  image {
    width: 34rpx;
    height: 34rpx;
  }
}
.edit-icon {
  width: 34rpx;
  height: 34rpx;
  margin-left: 20rpx;
}
.container-body {
  background: #fff;
  padding: 20rpx 30rpx;
  padding-bottom: 128rpx;
  .order-item {
    padding: 10rpx 0;
    display: flex;
    width: 100%;
  }
  .order-item-label {
    width: 138rpx;
    display: flex;
    justify-content: space-between;
    margin-right: 31rpx;
    color: #999999;
  }
  .order-item-value {
    flex: 1;
  }
}
.container-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15rpx 30rpx 25rpx 30rpx;
  background: #fff;
  display: flex;
  align-items: center;
  .u-btn {
    flex: 1;
    margin-right: 30rpx;
    &:last-child {
      margin-right: 0;
    }
  }
}
.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  z-index: 2;
  opacity: 0.8;
}
.custom-uni-field {
	/deep/ .uni-select {
		border: none;
		background: #f7f7f7;
		height: 88rpx;
	}
	/deep/ .uni-select__input-placeholder {
		font-size: 14px;
		color: #C1C4CB;
	}
}
.editTime-form {
  padding: 40rpx 30rpx;
}
.edit-form {
  padding: 40rpx 30rpx;
  min-height: 180rpx;
  // padding-bottom: 140rpx;
}
.uni-stat-box {
  margin-bottom: 140rpx;
}
.uni-stat__select {
  position: fixed;
  z-index: 1000;
  width: calc(100% - 130rpx);
  margin-bottom: 30rpx;
}
.uni-select__selector {
  width: calc(100% - 120px);
}
.custom-field {
  background: #f7f7f7;
  padding-left: 20rpx !important;
  padding-right: 20rpx !important;
  &.input {
    height: 88rpx;
    align-items: center;
  }
}

	/* 助店打卡选择助店的店面 */
	.store-select-shdow{
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		z-index: 88;
		background: rgba(0,0,0,0.3);
	}
	.store-select-toast{
		position: fixed;
		left: 50%;
		top: 200rpx;
		z-index: 99;
		margin-left: -345rpx;
		width: 690rpx;
		height: calc(100% - 400rpx);
		background: #FFFFFF;
		border-radius: 30rpx;
	}
	.toast-clone{
		position: absolute;
		top: -16rpx;
		right: -16rpx;
		width: 42rpx;
		height: 42rpx;
		background: url('../../static/toStore/clone.png') no-repeat center;
		background-size: 42rpx;
	}
	.store-search{
		display: flex;
		width: 620rpx;
		height: 98rpx;
		padding-left: 72rpx;
		background: url('../../static/toStore/search.png') no-repeat 30rpx 33rpx #F7F7F7;
		background-size: 32rpx;
		border-radius: 16rpx;
		margin: 53rpx auto 20rpx;
		align-items: center;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #333333;
		input{
			display: block;
			width: 100%;
			height: 100%;
		}
	}
	.scroll-Y{
		height: 100%;
	}
	.store-list{
		border-radius: 0 0 30rpx 30rpx;
		height: calc(100% - 171rpx);
		overflow: hidden;
	}
	.store-list-item{
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #555555;
		line-height: 48rpx;
		padding: 20rpx 35rpx;
		border-bottom: 1px solid #F2F2F2;
	}
</style>